package com.ygq.exportdbstructure.controller;

import com.ygq.exportdbstructure.model.DataSource;
import com.ygq.exportdbstructure.service.ExportDBService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.ygq.exportdbstructure.config.DataSourceValidator.initAndValidate;

/**
 * @author emc
 * @version 1.0
 * createTime 2025-10-29
 * description 控制器
 */
@RestController
@RequestMapping("/exportDB")
public class ExportDBController {

    private final ExportDBService exportDBService;

    public ExportDBController(ExportDBService exportDBService) {
            this.exportDBService = exportDBService;
    }

    /**
     * 获取版本号
     * @return 版本号
     */
    @RequestMapping("/VERSION")
    public String version() {
        return "V1.0.0";
    }

    /**
     * 测试数据库连接
     * @param dataSource 数据库连接信息
     * @return 连接结果
     */
    @PostMapping("/testDBSource")
    public String test(@RequestBody DataSource dataSource) {
        return exportDBService.getDBConnection(dataSource) == null ? "连接失败" : "连接成功";
    }

    /**
     * 获取表结构信息
     * @param dataSource 数据库连接信息
     * @return 表结构信息
     */
    @PostMapping("/getTableStructure")
    public ResponseEntity<byte[]> getTableStructureExcel(@RequestBody DataSource dataSource) {
        DataSource newDataSource = initAndValidate(dataSource);
        // 设置响应头
        String fileName = newDataSource.getDb_table_name() + "_structure.xlsx";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

        return ResponseEntity.ok()
                .headers(headers)
                .body(exportDBService.getTableStructureExcel(newDataSource));
    }
}
